<?php
/**
 * Created by PhpStorm.
 * User: wuchao
 * Date: 2020/4/3
 * Time: 15:30
 */

namespace app\api\model;

use \Exception;
use think\facade\Db;
use \think\response\Json;

class UserModel
{
    private static $_table = 'user'; // 用户表
    private static $_user_address_table = 'user_address'; // 用户地址表
    private static $_dirverTable = 'dirver'; // 司机表
    private static $_dirver_routeTable = 'dirver_route'; // 司机路由表

    /**微信注册登录
     * @param array $input
     */
    public static function Wxlogin($input)
    {
        if ($input['code']) {
            require_once '../sdk/WxpayAPI/lib/WxPay.Config.php';
            $appid = \WxPayConfig::APPID;
            $secret = \WxPayConfig::APPSECRET;
            $param["code"] = $input['code'];
            $param["grant_type"] = "authorization_code";
            $param["appid"] = $appid;
            $param["secret"] = $secret;
            $url = "https://api.weixin.qq.com/sns/oauth2/access_token?" . http_build_query($param);
            $data = self::curl_url($url);
            if (property_exists($data, 'errcode')) {
                return jsonFail('系统错误', $data);
            } else {
                $user_data = self::get_userinfo($data->openid, $data->access_token, $data->refresh_token, $input['state'],$input['admin_id']);
//                return $user_data;
                $rtn = makeToken('sxc','user-' . $user_data['openid']);
                if ($rtn == false) return jsonFail('生成登录态失败');
                return jsonSuccess('登录成功', ['tokeninfo' => $rtn, 'userinfo' => $user_data]);
            }
        } else {
            return jsonFail('获取Authorization_Code失败');
        }
    }

    /**用户登录|司机登录
     * @param array $input
     * @return Json
     */
    public static function login($input)
    {
        try {
            switch ($input['type']) {
                case 1://用户
                    $info = Db::table(self::$_table)->alias('a')
                        ->leftJoin(self::$_user_address_table . ' b', 'a.id = b.id')
                        ->field('a.id,a.status,a.pwd,b.id as address_id,b.name,b.phone,b.province,b.city,b.area,b.address,b.longitude,b.latitude,b.is_default')
                        ->where('a.account', $input['account'])
                        ->where('b.is_default', 1)
                        ->find();
                    break;
                case 2://司机
                    $info = Db::table(self::$_dirverTable)->alias('a')
                        ->leftJoin(self::$_dirver_routeTable . ' b', 'a.id = b.dirver_id')
                        ->field('a.*,b.id as dirverid,b.dirver_id,b.type,b.move_id,b.is_arrive,b.sort')
                        ->order('b.type')
                        ->order('b.sort')
                        ->where('a.account', $input['account'])
                        ->select()->toArray();
                    break;
                default:
                    return jsonFail('类型错误');
            }
            if (!$info) return jsonFail('未找到相关人员信息');
            if ($input['type'] == 1) {//用户登录
                if ($info['status'] != 1) return jsonFail('账号状态出错，请联系管理员处理');
                if (sha1($input['pwd']) !== $info['pwd']) return jsonFail('密码不正确');
                $rtn = makeToken('user-' . $info['id']);
                if ($rtn == false) return jsonFail('生成登录态失败');
                $info['token'] = $rtn;
                unset($info['pwd']);
                return jsonSuccess('登录成功', $info);
            } else {//司机登录
                if ($info[0]['status'] != 1) return jsonFail('账号状态出错，请联系管理员处理');
                $data = self::RemoveUser($info);
                if (sha1($input['pwd']) !== $info[0]['pwd']) return jsonFail('密码不正确');
                $rtn = makeToken('dirver-' . $info[0]['id']);
                if ($rtn == false) return jsonFail('生成登录态失败');
                $data['token'] = $rtn;
                return jsonSuccess('登录成功', $data);
            }
        } catch (Exception $e) {
            return jsonFail($e->getMessage());
        }
    }

    /**组合信息
     * @param array $input
     * @return Json
     */
    public static function RemoveUser($info)
    {
        foreach ($info as $key => $value) {
            $data['info']['id'] = $value['id'];
            $data['info']['name'] = $value['name'];
            $data['info']['sex'] = $value['sex'];
            $data['info']['age'] = $value['age'];
            $data['info']['status'] = $value['status'];
            $data['info']['phone'] = $value['phone'];
            $data['info']['create_time'] = $value['create_time'];
            unset($value['phone']);
            unset($value['account']);
            unset($value['name']);
            unset($value['sex']);
            unset($value['age']);
            unset($value['status']);
            unset($value['create_time']);
            unset($value['pwd']);
            unset($value['id']);
            $data['children'][] = $value;
        }
        return $data;
    }

    //微信授权回调根据Access_token获取指定用户信息
    public static function get_userinfo($openid, $access_token, $refresh_token, $state,$admin_id)
    {
        if ($access_token) {
            $param["openid"] = $openid;
            $param["access_token"] = $access_token;
            $url = "https://api.weixin.qq.com/sns/userinfo?" . http_build_query($param);
            $data = self::curl_url($url);
            return self::logins($data->sex,$data->openid, $data->nickname, $data->headimgurl, $access_token, $refresh_token, $state,$admin_id);
        }
    }

    //获取配置信息
    public static function logins($gender,$userid, $uname, $portrait, $access_token, $refresh_token, $state,$admin_id)
    {
        $data['openid'] = $userid;   // 账号参数
        $data['username'] = $uname;   // 用户名
        $data['portrait'] = $portrait;   // 头像访问
//        $data['access_token'] = $access_token;   // access_token码，一个月有效期
//        $data['refresh_token'] = $refresh_token;//access_token码过期后，刷新码，10年有效期
        $user_data = Db::table('user')->alias('a')
//            ->leftJoin('user_address b', 'a.id = b.uid')
            ->where('a.openid', $userid)
            ->where('a.status', 1)
            ->field('a.id,a.openid,a.username,a.portrait,a.pid,a.code,a.phone,a.gender,a.integral,a.admin_id,a.status')
            ->find();
        $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
        $orderSn = $yCode[intval(date('Y')) - 2011] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
        if (empty($user_data)) {
            $pid_user = [];
            if ($state) {//如果填写了邀请码
                $pid_user = Db::table('eb_user')->where('code', $state)->find();
            }
            try {
                $res = Db::table('user')->insert([
                    'pid' => $pid_user ? $pid_user['id'] : 0,
                    'code' => $orderSn,
                    'admin_id'=>$admin_id,
                    'openid' => $userid,
                    'username' => $uname,
                    'gender'=>$gender,
                    'portrait' => $portrait,
                    'access_token' => $access_token,
                    'refresh_token' => $refresh_token,
                    'create_time' => time(),
                ]);
                $data['code'] = $orderSn;
                return $data;
            } catch (\Exception $e) {
                return jsonFail($e->getMessage());
            }
        } else {
            $user_data['address_id'] = Db::table('user_address')->where('uid',$user_data['id'])->where('is_default',1)->field('id')->find();
            return $user_data;
        }
    }

    //curl进行Https Get访问链接
    public static function curl_url($url)
    {
        $ch = curl_init();
        //设置选项，包括URL
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);

        $output = curl_exec($ch); //执行并获取HTML文档内容
        $data = json_decode($output);
        //释放curl句柄
        curl_close($ch);
        return $data;
    }
}